package com.hhxy.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ghp
 * @date 2022/9/26
 * @Title
 * @description 用于获取Cookie信息，并将当前时间作为Cookie值发送给客户端
 */
@WebServlet("/lastAccessServlet")
public class LastAccessServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1、获取上一次访问本Servlet的时间
        //用于存储访问时间
        String lastAccessTime = null;
        //获取所有的Cookie
        Cookie[] cookies = request.getCookies();
        //遍历Cookie数组
        for (Cookie cookie : cookies) {
            //获取Cookie数组中键名为lastAccessTime的值
            if("lastAccessTime".equals(cookie.getName())){
                lastAccessTime = cookie.getValue();
            }
        }

        //2、向客户端发送上次访问的时间
        //设置响应数据的编码格式，防止中文乱码
        response.setContentType("text/html;charset=utf-8");

        //判断是否存在键名为lastAccessTime的Cookie
        if (lastAccessTime == null) {
            response.getWriter().write("您是首次访问本站");
        }else{
            response.getWriter().write("您上次访问的时间是："+lastAccessTime);
        }

        //3、将当前的时间作为Cookie的值发送给浏览器
        //获取当前的时间，并设置好格式
        String currentTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccessTime",currentTime);
        //设置Cookie在浏览器上的存活时间（3天）
        cookie.setMaxAge(60*60*24*3);
        response.addCookie(cookie);
    }
}